﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.ListFilter;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.NotePrint;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.Web.List;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace Fibot.YGJD.K3Cloud.Service.PlugIn
{
    /// <summary>
    /// DELIVERYNOTICE
    /// </summary>
    [HotUpdate]
    [Description("发货通知单自动生成打印pdf")]
    public class DeliveryNoticeScheduled : IScheduleService
    {

        public void Run(Context ctx, Schedule schedule)
        {
            string getAutoPrintNoticeSql = @"select FID,FBILLNO,FCREATEDATE from T_SAL_DELIVERYNOTICE tsd 
where F_LUZM_IsAutoAuditPrint = 1 AND FCREATEDATE > DATEADD(DAY,-1,GETDATE()) ";
            var needAutoPrintNoticeData = DBUtils.ExecuteDynamicObject(ctx, getAutoPrintNoticeSql);
            for (int i = 0; i < needAutoPrintNoticeData.Count; i++)
            {
                var item = needAutoPrintNoticeData[i];

                IDynamicFormView view = null;
                view = CreateView(ctx, "SAL_DELIVERYNOTICE");
                string[] tempIds = { "183c3813-453b-43b8-a1be-2d532cea8083" };
                string[] bills = { item["FID"].ToString() };
                PrintExportInfo pExInfo = new PrintExportInfo();
                pExInfo.PageId = view.PageId;
                pExInfo.FormId = view.BillBusinessInfo.GetForm().Id;
                pExInfo.BillIds = bills.ToList();//单据内码
                pExInfo.TemplateIds = tempIds.ToList();//套打模板ID
                pExInfo.FileType = ExportFileType.PDF;//文件格式
                pExInfo.ExportType = ExportType.ByPage;//导出格式
                string OutServicePath = string.Empty;
                string temppath = "D:\\";
                string filePath = Path.Combine(temppath, item["FBILLNO"].ToString() + ".PDF");
                pExInfo.ExportFileName = item["FBILLNO"].ToString() + ".PDF";
                pExInfo.FilePath = filePath;//文件输出路径
                Export(pExInfo, view);
            }
        }

        private void Export(PrintExportInfo pExInfo, IDynamicFormView view)
        {
            if (view is IListViewService)
            {
                ListView list = (ListView)view;
                list.ExportNotePrint(pExInfo);
            }
        }

        public IDynamicFormView CreateView(Context ctx, string formId)
        {
            FormMetadata _metadata = (FormMetadata)Kingdee.BOS.ServiceHelper.MetaDataServiceHelper.Load(ctx, formId);
            var OpenParameter = CreateOpenParameter(OperationStatus.VIEW, ctx, formId, _metadata);
            var Provider = GetListServiceProvider(OpenParameter);

            string importViewClass = "Kingdee.BOS.Web.List.ListView,Kingdee.BOS.Web";
            Type type = Type.GetType(importViewClass);
            IListViewService View = (IListViewService)Activator.CreateInstance(type);

            ((IListViewService)View).Initialize(OpenParameter, Provider);
            ((IListViewService)View).LoadData();
            return (IDynamicFormView)View;
        }
        private ListOpenParameter CreateOpenParameter(OperationStatus status, Context ctx, string formId, FormMetadata _metadata)
        {

            ListOpenParameter openPara = new ListOpenParameter(formId, _metadata.GetLayoutInfo().Id);
            Form form = _metadata.BusinessInfo.GetForm();
            openPara = new ListOpenParameter(formId, string.Empty);
            openPara.Context = ctx;
            openPara.ServiceName = form.FormServiceName;
            openPara.PageId = Guid.NewGuid().ToString();

            // 单据
            openPara.FormMetaData = _metadata;
            openPara.LayoutId = _metadata.GetLayoutInfo().Id;
            openPara.ListFormMetaData = (FormMetadata)FormMetaDataCache.GetCachedFormMetaData(ctx, FormIdConst.BOS_List);

            // 操作相关参数
            openPara.SetCustomParameter(FormConst.PlugIns, form.CreateListPlugIns());
            openPara.SetCustomParameter("filterschemeid", "");
            openPara.SetCustomParameter("listfilterparameter", new ListRegularFilterParameter());
            // 修改主业务组织无须用户确认
            openPara.SetCustomParameter("ShowConfirmDialogWhenChangeOrg", false);
            //openPara.SetCustomParameter("SessionManager", CommonSession.GetCurrent(ctx.UserToken).SessionManager);
            return openPara;
        }

        private IResourceServiceProvider GetListServiceProvider(DynamicFormOpenParameter param)
        {
            FormServiceProvider provider = new FormServiceProvider();
            provider.Add(typeof(IDynamicFormView), CreateListView(param));
            provider.Add(typeof(DynamicFormViewPlugInProxy), new ListViewPlugInProxy());
            provider.Add(typeof(DynamicFormModelPlugInProxy), new ListModelPlugInProxy());
            provider.Add(typeof(IDynamicFormModelService), GetListModel(param));
            provider.Add(typeof(IListFilterModelService), GetListFilterModel());
            var type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DefaultValue.DefaultValueCalculator,Kingdee.BOS.Business.DynamicForm");
            provider.Add(typeof(IDefaultValueCalculator), Activator.CreateInstance(type));
            // 注册IDBModelService
            type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DBModel.DBModelService,Kingdee.BOS.Business.DynamicForm");
            provider.Add(typeof(IDBModelService), Activator.CreateInstance(type));
            return provider;
        }

        ///


        /// 获取视图
        ///

        ///
        private IDynamicFormView CreateListView(DynamicFormOpenParameter param)
        {
            Form form = param.FormMetaData.BusinessInfo.GetForm();
            if (form.FormGroups != null && form.FormGroups.Count > 0)
            {
                return new TreeListView();
            }
            else
            {
                return new ListView();
            }
        }
        ///


        /// 获取视图模型
        ///

        ///
        private IDynamicFormModelService GetListModel(DynamicFormOpenParameter param)
        {
            Form form = param.FormMetaData.BusinessInfo.GetForm();
            if (form.FormGroups != null && form.FormGroups.Count > 0)
            {
                var type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.List.TreeListModel,Kingdee.BOS.Model");
                return (IDynamicFormModelService)Activator.CreateInstance(type);
            }
            else
            {
                var type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.List.ListModel,Kingdee.BOS.Model");
                return (IDynamicFormModelService)Activator.CreateInstance(type);
            }
        }
        ///


        /// 创建过滤条件模型
        ///

        ///
        private IListFilterModelService GetListFilterModel()
        {
            Type type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.ListFilter.ListFilterModel,Kingdee.BOS.Model");
            return (IListFilterModelService)Activator.CreateInstance(type);
        }
    }
}
